-- 删除缓存
local delCache = function (cacheData)
    local dataJson = cjson.decode(cacheData);
    local data = dataJson["data"];
    local tableNameKey = dataJson["tableNameKey"];
    local primaryKeyValue = dataJson["primaryKeyValue"];
    local bitMapKey = dataJson["mateDataBitMapKey"];
    local indexTable = dataJson["indexMap"];
    local mateDataVersionKey = dataJson["mateDataVersionKey"];
    local mateDataVersionValue = dataJson["mateDataVersionValue"];
    local mateDataIndexMap = dataJson["mateDataIndexMap"];
    local mateDataMaxIdKey = dataJson["mateDataMaxIdKey"];

    local isExecReplaceMaxId = false;
    local resultV = 1;

    local deleteCache = function ()
        redis.call("hdel", tableNameKey, primaryKeyValue);
        redis.call("set", mateDataVersionKey, mateDataVersionValue);

        local serverMaxId = redis.call("get", mateDataMaxIdKey);
        if(type(serverMaxId) == 'string' and tonumber(serverMaxId) > 0)
        then
            serverMaxId = tonumber(serverMaxId);
            while(true)
            do
                serverMaxId = serverMaxId - 1;
                if(redis.call("getbit", bitMapKey, serverMaxId) == 1)
                then
                   redis.call("set", mateDataMaxIdKey, serverMaxId);
                   break;
                end;

                if(serverMaxId <= 0)
                then
                    redis.call("set", mateDataMaxIdKey, 0);
                    break;
                end;
            end;
        end;

        -- TODO 删除有问题，索引与元数据一起删除。目前的问题是，索引删除正确，元数据未删除
        for key, value in pairs(mateDataIndexMap) do
            -- 查看索引是否再有值如果还存在值就不删除
            local tmpVal = typeConvert(value);
            local tmpKey = key .. ':' .. tmpVal;
            tmpKey = string.gsub(tmpKey, "matedata:", "", 1);

            if(redis.call("scard", tmpKey) > 1)
            then
                -- 个数大于1说明：索引还存在别的值，不能删除。元数据索引需要保留
                redis.call("srem", tmpKey, primaryKeyValue);
            else
                -- 个数小于等于0说明：索引不存在别的值，可以删除。元数据索引需要删除
                redis.call("srem", key, tmpVal);
                redis.call("del",  tmpKey);
            end;
        end;

        resultV = 0;
    end;

    local rollbackHandler = function ( err )
        redis.log(redis.LOG_NOTICE, mateDataVersionValue, "delCacheData >>>> script error info: ", err)
        resultV = 2;
    end;

    xpcall(deleteCache, rollbackHandler);

    --0: 执行成功   1:执行失败  2:未知错误
    return resultV;
end;